import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    redirect: "/home",
    component: HomeView
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: '/user/carts',
    component: () => import('../views/User.vue'),
    children: [
      {
        path: 'carts',
        component: () => import('../components/user/Cart.vue')
      }
    ],
    /*   beforeEnter: (to, from, next) => {
        // 路由独享守卫， 只有访问 user才触发
        console.log("路由独享守卫");
        let token = localStorage.getItem('x-auth-token');
        if (token) {
          next();
        } else {
          store.dispatch('ShowToast/asyncShowToast', {
            isShow: true,
            title: '请先登录',
            type: 'danger'
          })
        }
      } */
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../views/Details.vue')
  },
  {
    path: '*',
    component: () => import('../components/Error.vue')
  }
]

// 解决重复点击 路由错误
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫
// 去任何一个地方都会触发
/* router.beforeEach((to, from, next) => {
  //   to: Route : 即将要进入的目标 路由对象 (目标地址)
  // form: Route : 当前导航正要离开的路由 (当前离开的地址)
  // next: Function : 一定要调用该方法来 resolve 这个钩子 (下一步)

  // 需求：只有登录了才能打开个人中心页面
  if (to.path == '/user') {
    let token = localStorage.getItem('x-auth-token');
    if (token) {
      next();
    } else {
      // alert("请先登录")
      store.dispatch('ShowToast/asyncShowToast', {
        isShow: true,
        title: '请先登录',
        type: 'danger'
      })
    }
  } else {
    next()
  }
}) */

export default router
